package com.demoworld.rocketmq;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

/**
 * Description
 * <p>
 * </p>
 * DATE 2018/8/1.
 *
 * @author liwei5.
 */
public class RocketmqProducerInfo {
    public final DefaultMQProducer producer = new DefaultMQProducer("produce_group1");

    public RocketmqProducerInfo() throws MQClientException {
        producer.setNamesrvAddr("10.1.5.52:9876");
        producer.setInstanceName("producer_1");
        producer.start();
    }

    public SendResult send(String content, String topic) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        Message msg = new Message();
        msg.setTopic(topic);
        msg.setBody(content.getBytes());
        return producer.send(msg);
    }

    public void sendAsync(String content, String topic) throws RemotingException, MQClientException, InterruptedException {
        Message msg = new Message();
        msg.setBody(content.getBytes());
        msg.setTopic(topic);
        producer.send(msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("msg success, id=" + sendResult.getMsgId());
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("msg fail, ");
                throwable.printStackTrace();
            }
        });
    }
}
